package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.DBUtil;
import model.Job;
import model.LList;
import model.Puser;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

@WebServlet("/api/find-job-list.json")
public class FindDetail extends HttpServlet {
    private final ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String jid = req.getParameter("jid");
        String puid = null;
        List<LList> lis= new ArrayList<>();
        LList llist = new LList();
        Object result;
        result = new Object(){
            public boolean success = true;
            public Object data = lis;
        };
        try(Connection c = DBUtil.getConnection()) {
            {
            String sql = "SELECT * FROM job WHERE jid = ? ORDER BY puid  DESC";
            try (PreparedStatement s = c.prepareStatement(sql)) {
                s.setString(1, jid);
                try (ResultSet rs = s.executeQuery()) {
                    while (rs.next()) {

                        llist.puid = rs.getString("puid");
                        llist.title = rs.getString("title");
                        llist.salary=rs.getString("salary");
                        llist.contents = rs.getString("contents");
                        puid = rs.getString("puid");
                        lis.add(llist);
                    }
                }
            }
        }{
                String sql = "SELECT * FROM puser WHERE puid = ? ORDER BY puid  DESC";
                try (PreparedStatement s = c.prepareStatement(sql)) {
                    s.setString(1, puid);
                    try (ResultSet rs = s.executeQuery()) {
                        while (rs.next()) {

                            llist.pusername = rs.getString("pusername");
                            llist.phone = rs.getString("phone");
                            llist.email = rs.getString("email");
                           lis.add(llist);
                        }
                    }
                }
            }

        } catch (SQLException exception) {
            exception.printStackTrace();
        }
        String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(result);
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");
        resp.getWriter().println(json);
    }
}

